﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Agile.Engine.Data;

namespace Agile.Engine.Plus
{
    public class TableCreator
    {
        Agile.Engine.Xml.XmlResource Resource = new Xml.XmlResource()
        {
            ConfigUri = "assembly://Agile.Engine.Plus/Agile.Engine.Plus/SqlceResource.config"
        };


        public DataContext DataContext { get; set; }
        public string DbProvider { get; set; }

        public void CreateTable(System.Data.DataSet data)
        {
            var model = DataContext.DefaultModel;

            foreach (var r in data.Tables["SYS_TABLES"].AsEnumerable().AsParallel())
            {
                #region Table Create
                var type = r[2].ToString();
                if (type == "TABLE")
                {

                    var n = r[0].ToString();
                    var t = data.Tables[n];

                    foreach (DataColumn dc in t.Columns)
                    {
                        var cn = dc.ColumnName;
                        var split = cn.Split(new char[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries);
                        dc.ColumnName = split[1];
                    }

                    List<string> fields = new List<string>();
                    foreach (var f in t.AsEnumerable())
                    {
                        fields.Add(
                            Resource.Merge("field_merge", Agile.Engine.Utils.DataUtils.ToHashTable(f))
                            );
                    }

                    System.Collections.Hashtable m = new System.Collections.Hashtable();
                    m["TableName"] = n;
                    m["Fields"] = string.Join(",", fields.ToArray());
                    model.ExecuteTransaction(
                     new Action(() =>
                    {
                        var exist = Resource.Format((DbProvider == "System.Data.SqlClient") ? "sql_table_exist" : "sqlce_table_exist", n);
                        if (model.ExecuteScalar(0, exist) > 0)
                            model.ExecuteNonQuery(Resource.Format("table_drop", n));

                        var create = Resource.Merge("table_create", m);
                        foreach (var sql in create.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            model.ExecuteNonQuery(sql);
                        }

                        //DataContext.DataModel.UpdateTable("STABLE", "TABLEINDEX", r.ItemArray);
                        //DataContext.DataModel.UpdateTable("SFIELD", "FIELDINDEX", t.Select());
                    }
                    ));
                }
                #endregion
                #region Data

                else if (type == "DATA")
                {
                    var n = r[0].ToString();
                    var t = data.Tables[n];
                    var target = n.Substring(0, n.IndexOf("_"));

                    foreach (var dr in t.AsEnumerable())
                    {
                        if (Agile.Engine.Utils.StringUtils.IsEmpty(dr["SID"]))
                            dr["SID"] = Guid.NewGuid().ToString();
                        dr["SINDEXDATE"] = DateTime.Now;

                        dr.AcceptChanges();
                        dr.SetAdded();
                    }

                    DataContext.DefaultModel.UpdateTable(t, "SELECT * FROM " + target);

                }
                #endregion
            }


        }
    }
}
